<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

if(!class_exists('Api_honda')){
    class Api_honda extends CI_Controller {

        protected $_action = '';

        protected $_distance = 325;

        public function __construct(){
            parent::__construct();
            $this->load->model('Apilogmodel','m_api_log');
            $this->load->model('Usermodel','m_user');
            $this->load->model('Appmodel','m_app');
            $this->load->model('Hondacustomermodel','m_customer');
            $this->load->model('Hondalotterytimemodel','m_lottery_time');
            $this->load->model('configmodel','m_config');
            $this->load->database();


            $game_deadline = $this->m_config->getConfig(HONDA_DEADLINE);
            if(!empty($game_deadline) && strtotime($game_deadline) < time()) {
                $this->response->setDetail('活动已结束!');
                $this->response->responseExit();
            }

            // $this->_action = $this->uri->rsegments[1].'/'.$this->uri->rsegments[2];
            // if($this->session->userdata($this->_action) !== false) {
            //     $this->response->setDetail('请求太快，请稍后再试!');
            //     $this->response->responseExit();
            // }
            // $this->session->set_userdata($this->_action,true);
            // //api开头的不存
            if(is_string($this->uri->rsegments[2]) && stripos($this->uri->rsegments[2], 'api') === 0) {
                return;
            }
        }

        public function __destruct() {
            // $this->session->unset_userdata($this->_action);
            $customer = $this->session->userdata('honda_customer');
            $info = $this->input->post();
            $result = $this->response->getResult();
            @$this->m_api_log->createApiLog(array(
                'ip_address' => $this->input->ip_address(),
                'customer_id' => empty($customer) ? 0 :  $customer['customer_id'],
                'request_uri' => $_SERVER['REQUEST_URI'],
                'post_data' => json_encode($info,JSON_UNESCAPED_UNICODE),
                'result_data' => json_encode($result,JSON_UNESCAPED_UNICODE),
                'api_log_time_create' => NOW,
                'ua' => empty($_SERVER['HTTP_USER_AGENT']) ? '' : $_SERVER['HTTP_USER_AGENT'],
                // 'terminal' => TERMINAL_WEIXIN,
            ));

            $this->db->close();
        }


        public function initCustomer() {
            $this->validate->setRule('openid','string');
            $this->validate->setRule('openid','message',$this->lang->line('error_parameter'));
            $this->validate->setRule('openid_md5','string');
            $this->validate->setRule('openid_md5','message',$this->lang->line('error_parameter'));
            $this->validate->setRule('nickname','string');
            $this->validate->setRule('nickname','message',$this->lang->line('error_parameter'));
            $this->validate->setRule('sex','integer');
            $this->validate->setRule('sex','message',$this->lang->line('error_parameter'));
            $this->validate->setRule('province','string');
            $this->validate->setRule('province','notnull',false);
            $this->validate->setRule('province','message',$this->lang->line('error_parameter'));
            $this->validate->setRule('city','string');
            $this->validate->setRule('city','notnull',false);
            $this->validate->setRule('city','message',$this->lang->line('error_parameter'));
            $this->validate->setRule('country','string');
            $this->validate->setRule('country','notnull',false);
            $this->validate->setRule('country','message',$this->lang->line('error_parameter'));
            $this->validate->setRule('headimgurl','string');
            $this->validate->setRule('headimgurl','notnull',false);
            $this->validate->setRule('headimgurl','message',$this->lang->line('error_parameter'));
            if(!$this->validate->run($this->input->post(),true)){
                $this->response->setDetail($this->validate->getMessage());
                $this->response->responseExit();
            }
            $info = $this->validate->getResult();

            if(md5($info['openid'].FREEDOM_WAR_SALT) != $info['openid_md5']) {
                $this->response->setDetail('请勿恶意访问!');
                $this->response->responseExit();
            }
            unset($info['openid_md5']);



            $info['nickname'] = urlencode($info['nickname']);

            $customer = $this->m_customer->getCustomerByOpenid($info['openid']);
            if(!empty($customer) && $customer['customer_status'] == -2) {
                $this->response->setDetail('您存在恶意刷屏!');
                $this->response->responseExit();
            }
            if(empty($customer)) {
                $info['customer_time_create'] = NOW;
                $customer_id = $this->m_customer->createCustomer($info);
                if($customer_id == 0) {
                    $this->response->setDetail('初始化用户失败！请刷新页面！');
                    $this->response->responseExit();
                }
                $customer = $this->m_customer->getCustomer($customer_id);
            } else if($customer['nickname'] != $info['nickname'] || $customer['headimgurl'] != $info['headimgurl']){
                $info['customer_id'] = $customer['customer_id'];
                $this->m_customer->editCustomer($info);
                $customer = $this->m_customer->getCustomer($info['customer_id']);
            }
            $customer['nickname'] = urldecode($customer['nickname']);

            $this->session->set_userdata('honda_customer',$customer);

            $card_list = $this->m_customer->getCardListForCustomerId($customer['customer_id']);
            $customer['card_list'] = $card_list;

            $gift_code = $this->m_customer->getCodeForCustomer($customer['customer_id']);
            $customer['gift_code'] = $gift_code;

            $customer['available_lottery_time'] = $this->m_customer->getAvailableLotteryTime($customer['customer_id']);

            $this->response->setSuccess();
            $this->response->setDetail('提交成功!');
            $this->response->setAddon(array(
                'customer' => $customer,
            ));
            $this->response->responseExit();
        }

        private function _getRandomCode() {
        	$code = uniqid();
        	$str ='1234567890abcdefghijklmnopqrstuvwxyz';
        	$len = strlen($str);
        	for($i=0;$i<3;$i++) {
        		$code = $str[rand()%$len].$code;
        	}
        	return $code;
        }

        public function getCardNumber() {
            $customer = $this->session->userdata('honda_customer');
            if(empty($customer)) {
                $this->response->setDetail('初始化用户失败！请刷新页面重试！');
                $this->response->responseExit();
            }
            if($customer['customer_status'] == -2) {
                $this->response->setDetail('您存在恶意刷屏!');
                $this->response->responseExit();
            }

            $this->validate->setRule('card_type','integer');
            if(!$this->validate->run($this->input->post(),true)){
                $this->response->setDetail($this->validate->getMessage());
                $this->response->responseExit();
            }
            $info = $this->validate->getResult();
            if($info['card_type'] < 1 || $info['card_type'] > 4) {
            	$this->response->setDetail('参数错误!');
                $this->response->responseExit();
            }

            $card = $this->m_customer->getCardForCustomer($customer['customer_id'],$info['card_type']);

            if(empty($card)) {
            	$card_id = $this->m_customer->createCard(array(
                    'customer_id' => $customer['customer_id'],
            		'card_number' => $this->_getRandomCode(),
            		'card_type' => $info['card_type'],
            		'card_time_create' => NOW,
            	));
            	// card id unique
            	if($card_id == 0) {
            		$card_id = $this->m_customer->createCard(array(
                        'customer_id' => $customer['customer_id'],
	            		'card_number' => $this->_getRandomCode(),
	            		'card_type' => $info['card_type'],
	            		'card_time_create' => NOW,
	            	));
            	}
            	$card = $this->m_customer->getCard($card_id);
            }

            $available_lottery_time = $this->m_customer->getAvailableLotteryTime($customer['customer_id']);

            $this->response->setSuccess();
            $this->response->setDetail('提交成功!');
            $this->response->setAddon(array(
                'card' => $card,
                'available_lottery_time' => $available_lottery_time,
            ));
            $this->response->responseExit();
        }

        public function drawnLottery() {
            $customer = $this->session->userdata('honda_customer');
            if(empty($customer)) {
                $this->response->setDetail('初始化用户失败！请刷新页面重试！');
                $this->response->responseExit();
            }
            if($customer['customer_status'] == -2) {
                $this->response->setDetail('您存在恶意刷屏!');
                $this->response->responseExit();
            }

            $times = $this->m_customer->getAvailableLotteryTime($customer['customer_id']);
            if($times <= 0) {
            	$this->response->setDetail('你的抽奖机会已用完!');
            	$this->response->setCode(20001);
                $this->response->responseExit();
            }

            $info = array();

            // $time = time();
            // $last_time = $this->m_customer->getLastLotteryTime($customer['customer_id']);
            // if($time - $last_time < 15) {
            //     $this->m_customer->editCustomer(array(
            //         'customer_id' => $customer['customer_id'],
            //         'customer_status' => -2,
            //     ));
            //     $customer = $this->m_customer->getCustomer($customer['customer_id']);
            //     $customer['nickname'] = urldecode($customer['nickname']);
            //     $this->session->set_userdata('honda_customer',$customer);
            //     $this->response->setDetail('您存在恶意刷屏!');
            //     $this->response->responseExit();
            // }


            $lottery_result = 0;
            $lottery_time_id=0;
            $lotteryTime = $this->m_lottery_time->getCurrentLotteryTimeRate();
            if(!empty($lotteryTime)) {
            	$lottery_time_id = $lotteryTime['lottery_time_id'];
            	if(!$this->m_customer->checkHasLotteryGift($customer['customer_id'])) {
	            	$lottery_time_gift1_rate = floatval($lotteryTime['lottery_time_gift1_rate']);
	                $lottery_time_gift2_rate = floatval($lotteryTime['lottery_time_gift2_rate']);
	                $lottery_time_gift3_rate = floatval($lotteryTime['lottery_time_gift3_rate']);
	                $lottery_time_gift4_rate = floatval($lotteryTime['lottery_time_gift4_rate']);
	                $lottery_time_gift5_rate = floatval($lotteryTime['lottery_time_gift5_rate']);
	            }

                $baseNum = 1000000000;
	            $num = rand(1,$baseNum);

                if($customer['gift_type'] == 0) {
                	$rate = 0;
                	$rate += $lottery_time_gift1_rate;
                    if($lottery_result == 0 && $lottery_time_gift1_rate > 0 && $num <= $rate*$baseNum
                        && intval($lotteryTime['lottery_time_gift1_count']) > intval($lotteryTime['lottery_time_gift1_count_drawn'])) {
                        $lottery_result = 1;
                    }
                	$rate += $lottery_time_gift2_rate;
                    if($lottery_result == 0 && $lottery_time_gift2_rate > 0 && $num <= $rate*$baseNum
                        && intval($lotteryTime['lottery_time_gift2_count']) > intval($lotteryTime['lottery_time_gift2_count_drawn'])) {
                        $lottery_result = 2;
                    }
                	$rate += $lottery_time_gift3_rate;
                    if($lottery_result == 0 && $lottery_time_gift3_rate > 0 && $num <= $rate*$baseNum
                        && intval($lotteryTime['lottery_time_gift3_count']) > intval($lotteryTime['lottery_time_gift3_count_drawn'])) {
                        $lottery_result = 3;
                    }
                	$rate += $lottery_time_gift4_rate;
                    if($lottery_result == 0 && $lottery_time_gift4_rate > 0 && $num <= $rate*$baseNum
                        && intval($lotteryTime['lottery_time_gift4_count']) > intval($lotteryTime['lottery_time_gift4_count_drawn'])) {
                        $lottery_result = 4;
                    }
                }
            }

            $code = array();
            if($lottery_result > 1 && $lottery_result <=3 ) {
                $code = $this->m_customer->getAvailabelCode($lottery_result);
                if(empty($code)) {
                    $lottery_result = 0;
                } else {
                    $this->m_customer->editCode(array(
                        'customer_id' => $customer['customer_id'],
                        'code_id' => $code['code_id'],
                        'code_status' => STATUS_ACTIVE,
                        'code_time_active' => NOW,
                    ));
                }
            }

            //记录数据库
            $this->m_customer->createLotteryHistory(array(
                'customer_id' => $customer['customer_id'],
                'lottery_time_id' => $lottery_time_id,
                'gift_type' => $lottery_result,
                'gift_status' => ($lottery_result > 3 || $lottery_result==1)  ? STATUS_DISABLE : STATUS_ACTIVE,
                'lottery_time_time_create' => NOW,
                'code_id' => empty($code) ? 0 : $code['code_id'],
            ));


            $this->m_customer->updateCustomerLotteryCount($customer['customer_id']);

            if($lottery_result > 0) {
                $this->m_customer->editCustomer(array(
                    'customer_id' => $customer['customer_id'],
                    'gift_type' => $lottery_result,
                    'gift_status' => ($lottery_result > 3 || $lottery_result==1)  ? STATUS_DISABLE : STATUS_ACTIVE,
                	'lottery_time_id' => $lottery_time_id,
                    'customer_time_lottery' => NOW,
                ));
                $this->m_lottery_time->updateLotteryCountDrawn($lottery_time_id,$lottery_result);

            }

            $customer = $this->m_customer->getCustomer($customer['customer_id']);
            $customer['nickname'] = urldecode($customer['nickname']);
            $this->session->set_userdata('honda_customer',$customer);

            $available_lottery_time = $this->m_customer->getAvailableLotteryTime($customer['customer_id']);

            global $g_honda_game_gift;
            $addon = array();
            $addon['gift_type'] = $lottery_result;
            $addon['gift_name'] = id2name($lottery_result,$g_honda_game_gift);
            $addon['gift_code'] = $code;
            $addon['available_lottery_time'] = $available_lottery_time;

            $this->response->setSuccess();
            $this->response->setAddon($addon);
            $this->response->responseExit();
        }

       	public function submitReservation() {
       		$customer = $this->session->userdata('honda_customer');
            if(empty($customer)) {
                $this->response->setDetail('初始化用户失败！请刷新页面重试！');
                $this->response->responseExit();
            }
            if($customer['customer_status'] == -2) {
                $this->response->setDetail('您存在恶意刷屏!');
                $this->response->responseExit();
            }
            if($customer['customer_reservation_type'] != 0) {
            	$this->response->setDetail('您已预约，不能再次预约!');
                $this->response->responseExit();
            }

            $this->validate->setRule('customer_name','string');
            $this->validate->setRule('customer_name','notnull',false);
            $this->validate->setRule('customer_name','optional');
            $this->validate->setRule('customer_name','message','请填写您的姓名');
            $this->validate->setRule('customer_phone','string');
            $this->validate->setRule('customer_phone','optional');
            $this->validate->setRule('customer_phone','notnull',false);
            $this->validate->setRule('customer_phone','message','请填写您的手机号');
            $this->validate->setRule('shop_code','string');
            $this->validate->setRule('shop_code','message','请选择店面');
            $this->validate->setRule('customer_reservation_type','integer');
            $this->validate->setRule('customer_reservation_type','message','请选择预约类型');
            if(!$this->validate->run($this->input->post(),true)){
                $this->response->setDetail($this->validate->getMessage());
                $this->response->responseExit();
            }
            $info = $this->validate->getResult();

            // if(!preg_match("/^1[0-9]\d{9}$/i", $info['customer_phone'])){
            //     $this->response->setDetail('请输入正确的手机号码!');
            //     $this->response->responseExit();
            // }
            if(!empty($info['customer_phone'])) {
                if(!preg_match("/^1[0-9]\d{9}$/i", $info['customer_phone'])){
                    $this->response->setDetail('请输入正确的手机号码!');
                    $this->response->responseExit();
                }
                $tmpCustomer = $this->m_customer->getCustomerByPhone($info['customer_phone'],'customer_id');
                if(!empty($tmpCustomer) && $tmpCustomer['customer_id'] != $customer['customer_id']) {
                    $this->response->setDetail('此手机号码已参与过活动!');
                    $this->response->responseExit();
                }
            }

            if($info['customer_reservation_type'] < 1 || $info['customer_reservation_type'] > 2) {
                $this->response->setDetail('请选择正确的预约!');
                $this->response->responseExit();
            }

            $user = $this->m_user->getUserByCode($info['shop_code']);
            if(empty($user)) {
                $this->response->setDetail('请选择正确的店面!');
                $this->response->responseExit();
            }
            if($user['user_status'] != STATUS_ACTIVE) {
                $this->response->setDetail('该店面不能预约!');
                $this->response->responseExit();
            }
            if($info['customer_reservation_type'] == 1 && $user['shop_support_chezhu'] == 0) {
                $this->response->setDetail('店面【'.$user['user_name'].'】不支持车主讲堂!');
                $this->response->responseExit();
            }
            if($info['customer_reservation_type'] == 2 && $user['shop_support_shuangkuai'] == 0) {
                $this->response->setDetail('店面【'.$user['user_name'].'】不支持双快!');
                $this->response->responseExit();
            }

            $info['customer_id'] = $customer['customer_id'];
            $info['shop_id'] = $user['user_id'];
            unset($info['shop_code']);
            $this->m_customer->editCustomer($info);

            $customer = $this->m_customer->getCustomer($customer['customer_id']);
            $this->session->set_userdata('honda_customer',$customer);

            $this->response->setSuccess();
            $this->response->setDetail('提交预约成功!');
            $this->response->setAddon(array(
                'shop_name' => $user['user_name'],
                'shop_phone' => $user['shop_phone'],
            ));
            $this->response->responseExit();
       	}

        public function submitAddress() {
            $customer = $this->session->userdata('honda_customer');
            if(empty($customer)) {
                $this->response->setDetail('初始化用户失败！请刷新页面重试！');
                $this->response->responseExit();
            }
            if($customer['customer_status'] == -2) {
                $this->response->setDetail('您存在恶意刷屏!');
                $this->response->responseExit();
            }

            if($customer['gift_type'] == 0) {
                $this->response->setDetail('您还未中奖!');
                $this->response->responseExit();
            }

            $this->validate->setRule('customer_name','string');
            $this->validate->setRule('customer_name','message','请填您的姓名');
            $this->validate->setRule('customer_phone','string');
            $this->validate->setRule('customer_phone','message','请填您的手机号');
            if(!$this->validate->run($this->input->post(),true)){
                $this->response->setDetail($this->validate->getMessage());
                $this->response->responseExit();
            }
            $info = $this->validate->getResult();

            if(!preg_match("/^1[0-9]\d{9}$/i", $info['customer_phone'])){
                $this->response->setDetail('请输入正确的手机号码!');
                $this->response->responseExit();
            }

            $tmpCustomer = $this->m_customer->getCustomerByPhone($info['customer_phone'],'customer_id');
            if(!empty($tmpCustomer) && $tmpCustomer['customer_id'] != $customer['customer_id']) {
                $this->response->setDetail('此手机号码已参与过活动!');
                $this->response->responseExit();
            }

            $info['customer_id'] = $customer['customer_id'];
            $this->m_customer->editCustomer($info);

            $customer = $this->m_customer->getCustomer($customer['customer_id']);
            $this->session->set_userdata('honda_customer',$customer);

            $this->response->setSuccess();
            $this->response->setDetail('收货地址提交成功!');
            $this->response->responseExit();
        }

        public function getShop() {
            $this->load->driver('cache', array('adapter' => 'file'));
            $cache_file = 'shop_list.cache';
            $content = $this->cache->get($cache_file);

            if(!$content){
                list($user_list,$count) = $this->m_user->getUserListSection(array(
                    'where' => array('group_id' => 2,'user_status' => STATUS_ACTIVE,),
                ));
                // var_dump($user_list);
                $data = array('chezhu' => array(),'shuangkuai' => array());
                foreach($user_list as $k => $v) {
                    $type_list = array('chezhu','shuangkuai');
                    foreach($type_list as $k1 => $type) {
                        if($v['shop_support_'.$type] == 0) continue;
                        $isfindProvice = false;
                        foreach($data[$type] as $kp => $province) {
                            if($province['name'] == $v['user_province']) {
                                $isfindProvice = $kp;
                                break;
                            }
                        }
                        if($isfindProvice === false) {
                            $data[$type][] = array(
                                'name' => $v['user_province'],
                                'city' => array(
                                                array(
                                                    'name' =>  $v['user_city']
                                                    ,'shop' => array(
                                                        array(
                                                            'name' => $v['user_name'].'('.$v['shop_address'].')'
                                                            , 'code' => $v['user_code']
                                                        ),
                                                    ),
                                            ),
                                        )
                                    );
                        } else {
                            $isFindCity = false;
                            foreach($data[$type][$isfindProvice]['city'] as $kc => $city) {
                                if($city['name'] == $v['user_city']) {
                                    $isFindCity = $kc;
                                    break;
                                }
                            }
                            if($isFindCity === false) {
                                $data[$type][$isfindProvice]['city'][] = array(
                                        'name' =>  $v['user_city']
                                        ,'shop' => array(
                                            array('name' => $v['user_name'].'('.$v['shop_address'].')'
                                                    , 'code' => $v['user_code']))
                                        );
                            } else {
                                $isFindShop = false;
                                foreach($data[$type][$isfindProvice]['city'][$isFindCity]['shop'] as $ks => $shop) {
                                    if($city['name'] == $v['user_name'].'('.$v['shop_address'].')') {
                                        $isFindShop = $ks;
                                        break;
                                    }
                                }
                                if($isFindShop === false) {
                                    $data[$type][$isfindProvice]['city'][$isFindCity]['shop'][] =array('name' => $v['user_name'].'('.$v['shop_address'].')'  , 'code' => $v['user_code']);
                                }
                            }
                        }
                    }
                }
                $content = json_encode($data);
                $this->cache->save($cache_file,  $content, 7*24*60*60);
            } else {
                $data = json_decode($content);
            }
            echo 'var shopList='.json_encode($data,JSON_UNESCAPED_UNICODE);
        }

        public function dbview() {
            die();
            $data['desc'] = '清除本田数据';
            $data['ctrlName'] = $this->uri->rsegments[1];
            $this->load->view('zm/clear_db',$data);
        }
        public function clearDb(){
            die();
            $this->db->truncate('honda_customer'); 
            $this->db->truncate('honda_card');
            $this->db->truncate('honda_code');
            $this->db->truncate('honda_lottery_history');
            $this->db->truncate('honda_val_record');
            // $this->db->truncate('hd_game_lottery_time');
            // $this->db->truncate('hd_game_lottery_time_history');


            $this->response->setSuccess();
            $this->response->setDetail('清除成功!');
            $this->response->responseExit();
        }
    }

}
